package com.guonl.event.consume;

import com.alibaba.fastjson.JSON;
import com.guonl.enums.EventType;
import com.guonl.event.model.UserEvent;
import com.guonl.event.model.UserVO;
import com.guonl.plus.entity.IndexTUserPlus;
import com.guonl.plus.service.IIndexTUserPlusService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

@Slf4j
@Component
public class UserDataChangeConsume {

    @Autowired
    private IIndexTUserPlusService indexTUserPlusService;

    //    @Lazy
//    @Async
    @TransactionalEventListener(
            fallbackExecution = true,
            phase = TransactionPhase.AFTER_COMPLETION,
            classes = UserEvent.class)
    public void doAsync(UserEvent userEvent) {
        UserVO userVO = userEvent.getUserVO();
        EventType topic = userEvent.getTopic();
        log.info("[user 订阅:{}] - [开始执行:{}]", topic, JSON.toJSONString(userEvent));
        switch (topic) {
            case INSERT:
                saveOrUpdate(userVO);
                break;
            case UPDATE:
                saveOrUpdate(userVO);
                break;
        }

    }


    private void saveIndexTUserPlus(UserVO userVO) {
        IndexTUserPlus indexTUserPlus = new IndexTUserPlus();
        indexTUserPlus.setUserName(userVO.getUserName());
        indexTUserPlus.setPassword(userVO.getPassword());
        indexTUserPlus.setPhone(userVO.getPhone());
        indexTUserPlus.setStatus(userVO.getStatus());
        indexTUserPlus.setDepartmentName(userVO.getDepartmentName());
        indexTUserPlusService.save(indexTUserPlus);
    }

    private void updateIndexTUserPlus(UserVO userVO) {
        IndexTUserPlus indexTUserPlus = new IndexTUserPlus();
        indexTUserPlus.setUserId(Long.valueOf(userVO.getUserId()));
        indexTUserPlus.setUserName(userVO.getUserName());
        indexTUserPlus.setPassword(userVO.getPassword());
        indexTUserPlus.setPhone(userVO.getPhone());
        indexTUserPlus.setStatus(userVO.getStatus());
        indexTUserPlus.setDepartmentName(userVO.getDepartmentName());
        indexTUserPlusService.updateById(indexTUserPlus);
    }

    private void saveOrUpdate(UserVO userVO) {
        IndexTUserPlus indexTUserPlus = new IndexTUserPlus();

        Integer userId = userVO.getUserId();
        if (userId != null) {
            indexTUserPlus.setUserId(Long.valueOf(userId));
        }
        indexTUserPlus.setUserName(userVO.getUserName());
        indexTUserPlus.setPassword(userVO.getPassword());
        indexTUserPlus.setPhone(userVO.getPhone());
        indexTUserPlus.setStatus(userVO.getStatus());
        indexTUserPlus.setDepartmentName(userVO.getDepartmentName());
        indexTUserPlusService.saveOrUpdate(indexTUserPlus);
    }


}
